﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MSSClient.Utils;
using OpenCvSharp;

namespace MSSClient.OCR
{
    /// <summary>
    /// 用于定位发票的各项数据
    /// </summary>
    class PositionArea
    {
        static Boolean  debugTag = false;
        /// <summary>
        /// 去除发票的红色区域（印章）或者蓝色区域（内容），减少干扰
        /// </summary>
        /// <param name="tag">true-去除红色，false-去除蓝色</param>
        public static Mat WipeOffBuleOrRedArea(Boolean tag,string imaPath)
        {
            Mat src = Cv2.ImRead(imaPath);
            Mat gray = new Mat();
            Cv2.CvtColor(src, gray, ColorConversionCodes.RGB2GRAY);
            Mat matRB = new Mat();
            // 全局二值化
            int th = 180; //阈值要根据实际情况调整
            Mat binary = new Mat();
            Cv2.Threshold(gray, binary, th, 255, ThresholdTypes.Binary);

            Mat[] channels = null;
            Cv2.Split(src, out channels);
            if (tag)
            {
                matRB = channels[2];
                Cv2.Threshold(matRB, matRB, th, 255, ThresholdTypes.Binary);
            }
            else
            {
                matRB = channels[0];
                Cv2.Threshold(matRB, matRB, th, 255, ThresholdTypes.Binary);
            }
            Mat morphologyExMat = new Mat();
            Mat element = Cv2.GetStructuringElement(MorphShapes.Cross, new OpenCvSharp.Size(4, 4));
            Cv2.MorphologyEx(matRB, morphologyExMat, MorphTypes.Open, element);

            String name = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            if (debugTag)
            {
                if(tag)
                    Cv2.ImWrite("E:\\RedBule_binary\\bule_binary-" + name + ".jpg", morphologyExMat);
                else
                    Cv2.ImWrite("E:\\RedBule_binary\\red_binary-" + name + ".jpg", morphologyExMat);
            }
            CommonUtil.ClearMemory();
            return morphologyExMat;
        }
    }
}
